<template>
  <div class="room-management-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>房间管理</span>
          <el-button type="primary" @click="handleAddRoom" class="add-button">
            <el-icon-plus /> 添加房间
          </el-button>
        </div>
      </template>

      <div class="search-container">
        <el-input
          v-model="searchQuery"
          placeholder="请输入房间号、户型或状态"
          prefix-icon="Search"
          class="search-input"
        />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </div>

      <el-table v-loading="loading" :data="roomList" style="width: 100%">
        <el-table-column prop="id" label="房间ID" width="80" />
        <el-table-column prop="roomNumber" label="房间号" width="100" />
        <el-table-column prop="area" label="面积(㎡)" width="100" />
        <el-table-column prop="type" label="户型" width="100" />
        <el-table-column prop="orientation" label="朝向" width="100" />
        <el-table-column prop="floor" label="楼层" width="80" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === '空闲' ? 'success' : scope.row.status === '已租' ? 'danger' : 'warning'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currentTenant" label="当前租客" width="120" />
        <el-table-column prop="rent" label="租金(元/月)" width="120" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleViewDetail(scope.row)">查看详情</el-button>
            <el-button size="small" type="primary" @click="handleEditRoom(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDeleteRoom(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑房间对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="formData" ref="formRef" :rules="rules" label-width="100px">
        <el-form-item label="房间号" prop="roomNumber">
          <el-input v-model="formData.roomNumber" placeholder="请输入房间号" />
        </el-form-item>
        <el-form-item label="面积(㎡)" prop="area">
          <el-input v-model="formData.area" type="number" placeholder="请输入面积" />
        </el-form-item>
        <el-form-item label="户型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择户型">
            <el-option label="一室一厅" value="一室一厅" />
            <el-option label="两室一厅" value="两室一厅" />
            <el-option label="三室一厅" value="三室一厅" />
            <el-option label="三室两厅" value="三室两厅" />
          </el-select>
        </el-form-item>
        <el-form-item label="朝向" prop="orientation">
          <el-select v-model="formData.orientation" placeholder="请选择朝向">
            <el-option label="朝南" value="朝南" />
            <el-option label="朝北" value="朝北" />
            <el-option label="朝东" value="朝东" />
            <el-option label="朝西" value="朝西" />
            <el-option label="东南" value="东南" />
            <el-option label="西南" value="西南" />
          </el-select>
        </el-form-item>
        <el-form-item label="楼层" prop="floor">
          <el-input v-model="formData.floor" type="number" placeholder="请输入楼层" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option label="空闲" value="空闲" />
            <el-option label="已租" value="已租" />
            <el-option label="维修中" value="维修中" />
            <el-option label="保洁中" value="保洁中" />
          </el-select>
        </el-form-item>
        <el-form-item label="租金(元/月)" prop="rent">
          <el-input v-model="formData.rent" type="number" placeholder="请输入租金" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import roomService from '../../services/roomService.ts'

// 搜索相关
const searchQuery = ref('')

// 表格数据相关
const roomList = ref<any[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加房间')
const formData = reactive({
  id: '',
  roomNumber: '',
  area: '',
  type: '',
  orientation: '',
  floor: '',
  status: '空闲',
  currentTenant: '',
  rent: ''
})
const formRef = ref<any>(null)

// 表单验证规则
const rules = {
  roomNumber: [{ required: true, message: '请输入房间号', trigger: 'blur' }],
  area: [
    { required: true, message: '请输入面积', trigger: 'blur' },
    { type: 'number', message: '面积必须为数字', trigger: 'blur' },
    { min: 10, message: '面积不能小于10㎡', trigger: 'blur' }
  ],
  type: [{ required: true, message: '请选择户型', trigger: 'change' }],
  orientation: [{ required: true, message: '请选择朝向', trigger: 'change' }],
  floor: [
    { required: true, message: '请输入楼层', trigger: 'blur' },
    { type: 'number', message: '楼层必须为数字', trigger: 'blur' },
    { min: 1, message: '楼层不能小于1', trigger: 'blur' }
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  rent: [
    { required: true, message: '请输入租金', trigger: 'blur' },
    { type: 'number', message: '租金必须为数字', trigger: 'blur' },
    { min: 1000, message: '租金不能小于1000元', trigger: 'blur' }
  ]
}

// 生命周期钩子
onMounted(() => {
  fetchRoomList()
})

// 获取房间列表
const fetchRoomList = () => {
  loading.value = true
  roomService.getRoomList(currentPage.value, pageSize.value, searchQuery.value).then((res: any) => {
    if (res.code === 200) {
      roomList.value = res.data
      total.value = res.total
      loading.value = false
    }
  }).catch((error: any) => {
    console.error('获取房间列表失败:', error)
    ElMessage.error('获取房间列表失败')
    loading.value = false
  })
}

// 搜索事件
const handleSearch = () => {
  currentPage.value = 1
  fetchRoomList()
}

// 分页事件
const handleSizeChange = (size: number) => {
  pageSize.value = size
  fetchRoomList()
}

const handleCurrentChange = (current: number) => {
  currentPage.value = current
  fetchRoomList()
}

// 添加房间
const handleAddRoom = () => {
  dialogTitle.value = '添加房间'
  // 重置表单
  formData.id = ''
  formData.roomNumber = ''
  formData.area = ''
  formData.type = ''
  formData.orientation = ''
  formData.floor = ''
  formData.status = '空闲'
  formData.currentTenant = ''
  formData.rent = ''
  if (formRef.value) {
    formRef.value.resetFields()
  }
  dialogVisible.value = true
}

// 编辑房间
const handleEditRoom = (row: any) => {
  dialogTitle.value = '编辑房间'
  // 填充表单数据
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 查看详情
const handleViewDetail = (row: any) => {
  // 这里可以跳转到详情页或显示详情对话框
  ElMessage({
    message: `查看房间${row.roomNumber}的详情`,
    type: 'info'
  })
}

// 删除房间
const handleDeleteRoom = (id: number) => {
  roomService.deleteRoom(id).then((res: any) => {
    if (res.code === 200) {
      ElMessage({
        message: `删除房间ID: ${id} 成功`,
        type: 'success'
      })
      // 重新获取列表
      fetchRoomList()
    }
  }).catch((error: any) => {
    console.error('删除房间失败:', error)
    ElMessage.error('删除房间失败')
  })
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true
      if (formData.id) {
        roomService.updateRoom(Number(formData.id), formData).then((res: any) => {
          if (res.code === 200) {
            ElMessage({
              message: '编辑成功',
              type: 'success'
            })
            dialogVisible.value = false
            fetchRoomList()
          }
        }).catch((error: any) => {
          console.error('编辑房间失败:', error)
          ElMessage.error('编辑房间失败')
          loading.value = false
        })
      } else {
        roomService.createRoom(formData).then((res: any) => {
          if (res.code === 200) {
            ElMessage({
              message: '添加成功',
              type: 'success'
            })
            dialogVisible.value = false
            fetchRoomList()
          }
        }).catch((error: any) => {
          console.error('添加房间失败:', error)
          ElMessage.error('添加房间失败')
          loading.value = false
        })
      }
    }
  })
}
</script>

<style scoped>
.room-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.add-button {
  margin-top: 5px;
}

.search-container {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>